//需要在用户点击第一个框的按钮之后在执行下面这个函数
function box2_wordcloud() {
  // 使用fetch发送GET请求，获取图片列表
  fetch('/get_image_list')
    .then(response => response.json())
    .then(data => {
      // 获取图片列表
      const imageList = data.image_list;
      // 用文本渲染按钮
      renderButtons(imageList);
    })
    .catch(error => {
      console.error('Error:', error);
    });
  // 渲染按钮和下拉菜单
  function renderButtons(imageList) {
    // const deleteBtn = document.getElementById('deleteWord-button');
    //deleteBtn.textContent = '删除指定单词';
    const uploadButton = document.getElementById('upload-button');
    //找到前端中的dropdown-container元素在创建下拉框
    const dropdownContainer = document.getElementById('dropdown-container');
    // 创建下拉菜单的按钮
    const dropdownBtn = document.createElement('button');
    dropdownBtn.className = 'dropdown-btn dropdown-btn-width';
    dropdownBtn.style = 'z-index: 200;';
    dropdownBtn.textContent = '请选择选项';
    dropdownBtn.style.fontSize = '12px'; // 设置字体大小为1.2em
    dropdownContainer.appendChild(dropdownBtn);
    // console.log("123")
    // 创建下拉菜单内容容器
    const dropdownContent = document.createElement('div');
    dropdownContent.className = 'dropdown-content';
    dropdownContainer.appendChild(dropdownContent);
    let isDropdownVisible = false; // 记录下拉菜单是否可见的状态
    let wordToDelete; // 记录要删除的单词
    dropdownBtn.addEventListener('click', () => {
      if (isDropdownVisible) {
        dropdownContent.classList.remove('show');
      } else {
        dropdownContent.classList.add('show');
      }
      isDropdownVisible = !isDropdownVisible; // 切换下拉菜单可见状态
    });
    // 遍历图片列表，将图片渲染为下拉菜单的选项
    imageList.forEach(imageUrl => {
      const optionBtn = document.createElement('button');
      optionBtn.textContent = imageUrl;
      optionBtn.textStyle = "color:white;background-color: #325f97";
      optionBtn.addEventListener('click', () => {
        getImageData(imageUrl, wordToDelete);
      });
      dropdownContent.appendChild(optionBtn);
    });
    //监听删除按钮的点击事件
    // deleteBtn.addEventListener('click', () => {
    //   wordToDelete = window.prompt('请输入要剔除的单词,注意用;隔开');
    // });
    // 监听上传按钮的点击事件
    uploadButton.addEventListener('click', () => {
      // 创建文件选择的input元素
      console.log("shangchuan")
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = '.png';
      // 监听文件选择的change事件
      fileInput.addEventListener('change', () => {
        const file = fileInput.files[0];
        // 创建文件读取器
        const reader = new FileReader();
        reader.onload = (event) => {
          const base64Data = event.target.result;
          // 绘制词云图形
          drawWordCloud(base64Data, wordToDelete);
        };
        // 读取文件为base64数据
        reader.readAsDataURL(file);
      });
      // 触发文件选择对话框
      fileInput.click();
    });
    // 监听下载按钮的点击事件
    const downloadButton = document.getElementById('download-button-map');
    downloadButton.addEventListener('click', () => {
      console.log("下载词云图")
      downloadWordCloudImage();
    });
    // 下载词云图函数
    function downloadWordCloudImage() {
      const wordCloudContainer = document.getElementById('wordcloud-container');
      const canvas = wordCloudContainer.querySelector('canvas');
      const image = canvas.toDataURL('image/png');
      const link = document.createElement('a');
      link.href = image;
      link.download = 'wordcloud.png';
      link.click();
    }
  }
  // 获取图片数据
  function getImageData(imageUrl, wordToDelete) {
    // 使用fetch发送POST请求，获取Base64图片数据
    fetch('/get_base64_image', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ 'image_name': imageUrl })
    })
      .then(response => response.json())
      .then(data => {
        const base64Data = data.base64_data;
        // 在这里可以使用Base64图片数据进行操作，例如将其显示在页面上或下载
        drawWordCloud('data:image/png;base64,' + base64Data, wordToDelete);
        // 隐藏下拉菜单
        const dropdownContent = document.querySelector('.dropdown-content');
        dropdownContent.classList.remove('show');
      })
      .catch(error => {
        console.error('Error:', error);
      });
  }
  //删除用户输入单词的函数
  function deleteWordFromData(data, wordsToDelete) {
    if (typeof wordsToDelete === 'undefined') {
      return data; // 如果 wordsToDelete 为 undefined，直接返回原始数组
    }
    // 将用户输入的单词字符串拆分成单词数组
    var wordsArray = wordsToDelete.split(';');
    // 删除匹配的单词（不区分大小写）
    return data.filter(item => !wordsArray.some(word => item.name.toLowerCase() === word.toLowerCase()));
  }
  //绘制词云图函数
  function drawWordCloud(base64_data, wordToDelete) {
    //console.log(wordToDelete);//wordToDelete有两种情况一是用户输入了 二是undefined
    var data = wordcloudData_final;
    var updatedata = deleteWordFromData(data, wordToDelete);
    //var values = Object.values(data); // 获取权重值数组
    var values = Object.values(updatedata); // 获取权重值数组
    var minWeight = Math.min(...values); // 获取最小权重值
    var maxWeight = Math.max(...values); // 获取最大权重值
    var weightRange = [minWeight, maxWeight]; // 权重范围数组
    var fontSizeRange = [5, 40];
    // 根据权重值映射到字体大小
    function mapWeightToFontSize(weightList) {
      var fontSizeList = [];
      for (var i = 0; i < weightList.length; i++) {
        var weight = weightList[i];
        var normalizedWeight = (weight - weightRange[0]) / (weightRange[1] - weightRange[0]);
        var fontSize = fontSizeRange[0] + normalizedWeight * (fontSizeRange[1] - fontSizeRange[0]);
        fontSizeList.push(fontSize);
      }
      return fontSizeList;
    }
    var fontSize = mapWeightToFontSize(values);
    var myChart = echarts.init(document.getElementById('wordcloud-container'));
    var maskImage = new Image();
    maskImage.src = base64_data;
    maskImage.onload = function () {
      myChart.setOption({
        backgroundColor: "transparent",
        tooltip: {
          backgroundColor: 'rgba(0, 0, 0, 0)', // 设置Tooltip的背景色
          borderColor: '#333', // 设置Tooltip的边框颜色
          formatter: function (params) {
            return '权重: ' + params.data.value;
          }
        },
        series: [
          {
            type: "wordCloud",
            // 鼠标拖动事件监听
            emphasis: {
              focus: 'self', // 只对当前词进行放大处理
              textStyle: {
                fontSize: 55, // 设置放大后的字体大小
              },
              itemStyle: {
                shadowColor: 'rgba(0, 0, 0, 0)',
                shadowBlur: 0
              }
            },
            // 鼠标移出事件监听
            normal: {
              textStyle: {
                fontSize: 10 // 恢复正常大小的字体大小
              }
            },
            gridSize: 3,//用来调整词之间的距离
            //shape: 'cardioid',
            //sizeRange: [6, 55],//用来调整字的大小范围
            rotationRange: [0, 0],//用来调整词的旋转方向，，[0,0]--代表着没有角度，也就是词为水平方向，需要设置角度参考注释内容
            rotationStep: 90,
            drawOutOfBound: false,// 允许词太大的时候，超出画布的范围
            layoutAnimation: false,// 布局的时候是否有动画
            maskImage: maskImage,//用来设置词云图的形状
            textStyle: {          //用来设置词的样式
              fontSize: fontSize,
              fontFamily: 'sans-serif',
              fontWeight: 'bold',
              color: function () {
                return 'rgb(' + [
                  Math.round(Math.random() * 250),
                  Math.round(Math.random() * 250),
                  Math.round(Math.random() * 250)
                ].join(',') + ')';
              }
            },
            left: "center",        //位置相关设置
            top: "center",
            right: null,
            bottom: null,
            data: updatedata
          }
        ]
      })
    }
  }
}


function test() {          //key为关键词
  fetch('/data_wordcloud')
    .then(response => response.json())
    .then(result => {
      wordcloudData_final = result;
      // var clear_button = document.getElementById('dropdown-container');
      // clear_button.innerHTML = '';
      box2_wordcloud();//绘制词云
    })
    .catch(error => {
      console.error('Error:', error);
    });
  function downloadFile(content, fileName, format) {
    const blob = new Blob([content], { type: `text/${format}` });
    const downloadLink = document.createElement('a');
    downloadLink.href = URL.createObjectURL(blob);
    downloadLink.download = `${fileName}.${format}`;
    downloadLink.click();
  }

}
test();
